﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace SharpCmd.IO
{
    /// <summary>
    /// Provides information about file system object
    /// </summary>
    internal class FSObjectInfo
    {
        public const int DirectoryInitialSize = -1;

        #region cctor
        static FSObjectInfo()
        {
            SizeFormatInfo = new NumberFormatInfo();
            SizeFormatInfo.NumberGroupSeparator = ",";
            SizeFormatInfo.NumberGroupSizes = new int[] { 3 };
            SizeFormatInfo.NumberDecimalDigits = 0;
            DateTimeFormatInfo = new DateTimeFormatInfo();
        }
        #endregion

        #region properties
        public static NumberFormatInfo SizeFormatInfo { get; set; }
        public static DateTimeFormatInfo DateTimeFormatInfo { get; set; }
        public FSObjectType Type { get; set; }

        public string Name { get; set; }
        public string Extension { get; set; }
        public string FullName { get; set; }
        public long Size { get; set; }
        public DateTime LastWriteTime { get; set; }
        public FileAttributes Attributes { get; set; }
        public FSObjectAction Action { get; set; }

        /// <summary>
        /// If this item is a fake entry, e.g. ".." directory
        /// </summary>
        public bool Fake { get; set; }

        public bool AlwaysOnTop { get; set; }
        #endregion

        public string DisplayString
        {
            get { return Type == FSObjectType.Directory ? "[" + this.Name + "]" : this.Name; }
        }

        public string SizeString
        {
            get { return Size >= 0 ? string.Format(SizeFormatInfo, "{0:N}k", this.Size / 1024) : string.Empty; }
        }

        public string FullDetails
        {
            get { return string.Format("{0}.{1} {2} {3:u} {4}", this.Name, this.Extension, this.SizeStringDir, this.LastWriteTime, this.AttributeString); }
        }

        public string FullDetailsFullPath
        {
            get { return string.Format("{0} {1} {2:u} {3}", this.FullName, this.SizeStringDir, this.LastWriteTime, this.AttributeString); }
        }

        public string SizeStringDir
        {
            get { return Size >= 0 ? string.Format(SizeFormatInfo, "{0:N}k", Size / 1024) : "DIR"; }
        }

        public string NameWithExtension
        {
            get
            {
                if (string.IsNullOrEmpty(this.Extension))
                    return this.Name;
                else
                    return this.Name + "." + this.Extension;
            }
        }

        public string AttributeString
        { // rahs[ce]
            get
            {
                return string.Format(
                    "{0}{1}{2}{3}",
                    (Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly ? 'r' : '-',
                    (Attributes & FileAttributes.Hidden) == FileAttributes.Hidden ? 'h' : '-',
                    (Attributes & FileAttributes.System) == FileAttributes.System ? 's' : '-',
                    (Attributes & FileAttributes.Compressed) == FileAttributes.Compressed ? 'c' : (Attributes & FileAttributes.Encrypted) == FileAttributes.Encrypted ? 'e' : '-');
            }
        }

        #region static methods

        public static FSObjectInfo FromDirectoryInfo(DirectoryInfo info, FSObjectAction action)
        {
            return new FSObjectInfo()
            {
                FullName = info.FullName,
                Name = info.Name,
                Size = FSObjectInfo.DirectoryInitialSize,
                LastWriteTime = info.LastWriteTime,
                Type = FSObjectType.Directory,
                Attributes = info.Attributes,
                Action = action
            };
        }

        public static FSObjectInfo FromDirectoryInfo(DirectoryInfo info)
        {
            return FromDirectoryInfo(info, FSObjectAction.None);
        }

        public static FSObjectInfo FromFileInfo(FileInfo info, FSObjectAction action)
        {
            return new FSObjectInfo()
            {
                FullName = info.FullName,
                Name = System.IO.Path.GetFileNameWithoutExtension(info.FullName),
                Extension = info.GetExtension(),
                Size = info.Length,
                LastWriteTime = info.LastWriteTime,
                Type = FSObjectType.File,
                Attributes = info.Attributes,
                Action = action
            };
        }

        public static FSObjectInfo FromFileInfo(FileInfo info)
        {
            return FromFileInfo(info, FSObjectAction.None);
        }

        /// <summary>
        /// Gets all infos from other infos
        /// </summary>
        /// <param name="DirectoriesLast">IF true, directories are put after their files, so deletion can work</param>
        public static List<FSObjectInfo> GetAllInfosRecursive(List<FSObjectInfo> infos, FSObjectAction action)
        {
            List<FSObjectInfo> newInfos = new List<FSObjectInfo>();
            foreach (FSObjectInfo info in infos)
            {
                if (info.Type == FSObjectType.File)
                {
                    newInfos.Add(info);
                    continue;
                }

                // if it's a directory, traverse its contents
                AddDirectoryToList(info.FullName, newInfos, action);
            }
            return newInfos;
        }
        #endregion

        public string[] GetFullInfos()
        {
            const int FULLINFOS_COUNT = 5;
            string[] strings = new string[FULLINFOS_COUNT];
            strings[0] = this.Name;
            strings[1] = this.Extension;
            strings[2] = this.SizeString;
            strings[3] = this.LastWriteTime.ToString("u");
            strings[4] = this.AttributeString;
            return strings;
        }

        public void SetSize(long size)
        {
            this.Size = size;
        }

        public string ToFullString()
        {
            return Type == FSObjectType.Directory ? "[" + this.Name + "]" : this.NameWithExtension;
        }

        public override string ToString()
        {
            return Name;
        }

        /// <summary>
        /// adds directory, subdirectories and files to the list
        /// </summary>
        private static void AddDirectoryToList(string directoryName, List<FSObjectInfo> newInfos, FSObjectAction action)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
            if ((action & FSObjectAction.Copy) == FSObjectAction.Copy)
                newInfos.Add(FSObjectInfo.FromDirectoryInfo(dirInfo, FSObjectAction.Copy));
            var subdirs = Directory.GetDirectories(directoryName);
            foreach (var subdir in subdirs)
                AddDirectoryToList(subdir, newInfos, action);
            newInfos.AddRange(dirInfo.GetFiles().OrderBy(p => p.Name).Select(p => FSObjectInfo.FromFileInfo(p)));
            if ((action & FSObjectAction.Delete) == FSObjectAction.Delete)
                newInfos.Add(FSObjectInfo.FromDirectoryInfo(dirInfo, FSObjectAction.Delete));
        }
    }
}